
#include "stm32f4xx_hal.h"
#include "extern_sram.h"
#include "uart.h"
#include "lcd.h"
#include "timer.h"
#include "touch.h"
#include "board.h"

#include "lvgl.h"
#include "lv_port_disp.h"
#include "lv_port_indev.h"
#include "lv_demo_widgets.h"

#define LED0_PORT    GPIOE
#define LED0_PIN     GPIO_PIN_3
#define LED1_PORT    GPIOE
#define LED1_PIN     GPIO_PIN_4
#define LED2_PORT    GPIOG
#define LED2_PIN     GPIO_PIN_9

static void my_lv_log(const char *buf)
{
    xprintf("%s\r\n", buf);
}

void MX_GPIO_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    GPIO_InitStruct.Pin = LED0_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Alternate = 0;
    HAL_GPIO_Init(LED0_PORT, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = LED1_PIN;
    HAL_GPIO_Init(LED1_PORT, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = LED2_PIN;
    HAL_GPIO_Init(LED2_PORT, &GPIO_InitStruct);

}

int main(void)
{
    SCB->VTOR = FLASH_BASE | 0x8000;

    HAL_Init();
    SystemClock_Config();
    MX_GPIO_Init();
    MX_FSMC_Init();
    MX_USART6_UART_Init();
    HwMicroTimerInit();

    xprintf("System initialized.\r\n");

    xprintf("Testing extern SRAM ...");
    if (test_extern_sram()) {
        xprintf("failed!\r\n");
    } else {
        xprintf("passed!\r\n");
    }

    xprintf("LVGL initializing ...");
    lv_init();
    lv_log_register_print_cb(my_lv_log);
    lv_port_disp_init();
    lv_port_indev_init();
    lv_demo_widgets();
    xprintf("done!\r\n");

    uint32_t count = 0;
    while (1)
    {
        if (count ++ >= 100) {
            HAL_GPIO_TogglePin(LED0_PORT, LED0_PIN);
            HAL_GPIO_TogglePin(LED1_PORT, LED1_PIN);
            HAL_GPIO_TogglePin(LED2_PORT, LED2_PIN);
            count = 0;
        }
        lv_task_handler();
        HAL_Delay(5);
    }
}

void SysTick_Handler(void)
{
    HAL_IncTick();
    lv_tick_inc(1);
}
